package LeetCode;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by kechelle on 2020/8/12 13:19
 * 两数之和
 * 示例:
 * 给定 nums = [2, 7, 11, 15], target = 9
 * 因为 nums[0] + nums[1] = 2 + 7 = 9
 * 所以返回 [0, 1]
 */
public class Code1 {

    public int[] twoSum(int[] nums, int target) {
        Map<Integer,Integer> map = new HashMap<>();
        for (int i=0;i<nums.length;i++){
            int key = target - nums[i];
            if (map.containsKey(key)){
                return new int[]{map.get(key),i};
            }
            map.put(nums[i],i);
        }
        throw new IllegalArgumentException("没有这样的结果");
    }

    public static void main(String[] args) {
        int[] nums = {2, 7, 11, 15};
        Code1 code1 = new Code1();
        System.out.println(code1.twoSum(nums,9));
    }

}
